﻿define('ui/markerList/emissionML', 
	['ui/controller/conditionController', 'ui/controller/permitActualController',
	 'api/emissionService', 'ui/gis'], 
	function(conditionController, permitActualController, emissionService, gis) {

	
	/**
	 * 排放量MarkerList，包含以下功能：
	 * 1、地图上全省的许可证数量汇总，按到期时间区间段来划分
	 * 2、左侧面板企业列表元素自定义渲染：各地市许可证到警预期企业数量；各企业许可证有效开始结束时间、是否超期
	 * 3、地图点位信息：叠加echart饼状图、自定义企业点位信息
	 * 4、点击地图上饼状图，渲染该地市下的企业点位信息；收缩地图后，点位信息消失、渲染饼状图
	 * 5、包含的数据：
	 * 1）各地市饼状图数据与企业(sublist)点位数据数组，查看goPage方法请求的后台JSON数据
	 * 2）markerList属性，加载的MarkerList对象
	 * 3）cityData数组，地市许可证的数量，内部对象带有arealeve标记；cityDataLength为cityData数组长度
	 * 4）inited，MarkerList首次加载标记，用于cityData数组首次加载，为false则把地市的数据加到该数组中
	 * 5）cityMarker数组，地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
	 * 6）sublist数组，所有企业点位数据，用于地图放大到一定级别后显示，该功能目前暂时不用
	 */
	var emissionML = {
			
		markerList : null,	
		
		//所有的自定义饼状图marker是否渲染完成的一个标记，用cityDataLength做依据来判断
		inited: false,
		
		//后台地市数据数组
		cityData: [],
		//后台地市数据数组长度
		cityDataLength: 0,
		//地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
		cityMarker:[],
		//所有企业点位数据，用于地图放大到一定级别后显示
		sublist:[],
		
		/**
		 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList，从最外层的地图饼状图开始渲染
		 */
		goPage: function(page) {
			/*var d = new Date();
			var expireTime;
	    	var year = conditionController.getYearCode()?conditionController.getYearCode():d.getFullYear();
	    	if(year == d.getFullYear()) {
	    		expireTime = year+'-'+ (d.getMonth()+1) +'-'+ d.getDate();
	    		expireTime = '2020-7-12';
	    	}else {
	    		expireTime = year+'-12-31';
	    	}
	        ajaxProcess({
	            url : '/pls/gis/licence/warning',
	            requestType : 'POST',
	            data : {
	            	expireTime : expireTime
	            },
	            successHandle : function(res) {
	            	//console.log(res);
	            	
	            	emissionML.clearData();
	            	
	            	var data = res.rows;
	            	var t;
	            	var d = [];
	            	for(var i=0; i<data.length; i++) {
	            		if(data[i].areaLevel=='province'){
	            			t = data[i];
	            		}else if(data[i].areaLevel=='city') {
	            			d.push(data[i]);
	            			for(var j=0; j<data[i].sublist.length;j++) {
	            				emissionML.sublist.push(data[i].sublist[j]);
	                    	}
	            		}
	            	}
	            	//console.log('emissionML goPage：');
	            	//console.log(d);
	            	emissionML.cityData = d;
	            	emissionML.cityDataLength = d.length;
	            
	            	emissionML.markerList.render(d);
	            }
	        });*/
	        
	        ajaxProcess({
	            url : '/pls/gis/emission/polyList',
	            requestType : 'POST',
	            async:false,
	            data : {
	            	arealevel:'2',
	            	areacode:'',
	            	pareacode:'',
	            	year:'',
	            	pollutecode:''
	            },
	            successHandle : function(res) {
	            	emissionML.clearData();
	            	
	            	var data = res.rows;
	            	var total = 0;
	            	for(var i=0; i<data.length; i++) {
	            		total += data[i].estdata;
	            	}
	            	for(var i=0; i<data.length; i++) {
	            		data[i]['count'] = (1==1?data[i].estdata:data[i].realdata);
	            		data[i]['rate'] = (data[i]['count']/total).toFixed(2);
	            		data[i]['total'] = total;
	            		data[i]['sublist'] = [];
	            	}
	            	emissionML.cityData = data;
	            	emissionML.cityDataLength = data.length;
	            }
	        });
	        
	        ajaxProcess({
	            url : '/pls/gis/emission/polyList',
	            requestType : 'POST',
	            async:false,
	            data : {
	            	arealevel:'3',
	            	areacode:'',
	            	pareacode:'',
	            	year:'',
	            	pollutecode:''
	            },
	            successHandle : function(res) {
	            	
	            	var data = res.rows;
	            	var total = 0;
	            	for(var i=0; i<emissionML.cityData.length; i++) {
	            		var cityData = emissionML.cityData[i];
	            		for(var j=0; j<data.length; j++) {
	            			data[j]['count'] = (1==1?data[j].estdata:data[j].realdata);
	            			data[j]['rate'] = (data[j]['count']/cityData.total).toFixed(2);
	            			data[j]['total'] = cityData.total;
	            			data[j]['sublist'] = [];
	            			if(data[j].pareacode==cityData.areacode) {
	            				cityData['sublist'].push(data[j]);
	            			}
	            		}
	            	}
	            	
	            	console.log(emissionML.cityData);
	            }
	        });
	        
	        
	       /* ajaxProcess({
	            url : '/pls/gis/emission/multiPointList',
	            requestType : 'POST',
	            async:false,
	            data : {
	            	arealevel:'',
	            	areacode:'',
	            	pareacode:'',
	            	year:'',
	            	pollutecode:''
	            },
	            successHandle : function(res) {
	            	
	            	var data = res.rows;
	            	var total = 0;
	            	for(var i=0; i<emissionML.cityData.length; i++) {
	            		var cityData = emissionML.cityData[i];
	            		for(var i=0; i<emissionML.cityData['sublist'].length; i++) {
		            		var subCityData = emissionML.cityData[i];
		            		for(var j=0; j<data.length; j++) {
		            			data[j]['count'] = (1==1?data[j].estdata:data[j].realdata);
		            			data[j]['rate'] = (data[j]['count']/subCityData.total).toFixed(2);
		            			data[j]['total'] = subCityData.total;
		            			data[j]['sublist'] = [];
		            			if(data[j].pareacode==subCityData.areacode) {
		            				subCityData['sublist'].push(data[j]);
		            			}
		            		}
		            	}
	            	}
	            	
	            	console.log(emissionML.cityData);
	            }
	        });*/
	        
	        emissionML.markerList.render(emissionML.cityData);
	    },
		
	    /**
	     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
	     */
		load: function(){
			emissionML.clearData();
			AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
			    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

			    //即jQuery/Zepto
			    var $ = MarkerList.utils.$;

			    var defaultIconStyle = 'red', //默认的图标样式
			        hoverIconStyle = 'green', //鼠标hover时的样式
			        selectedIconStyle = 'purple' //选中时的图标样式
			    ;

			    var markerList = new MarkerList({
			        map: gis.map,
			        //ListElement对应的父节点或者ID
			        listContainer: "enterpriseList",
			        //选中后显示

			        //从数据中读取位置, 返回lngLat
			        getPosition: function(item) {
			        	if(item.longitude && item.latitude) {
			        		return [item.longitude, item.latitude];
			        	}
			        	return [108.372564, 22.823606];
			        	//return item.location;
			        },
			        //数据ID，如果不提供，默认使用数组索引，即index
			        getDataId: function(item, index) {

			            return item.id;
			        },
			        getInfoWindow: function(data, context, recycledInfoWindow) {
			        	//console.log("窗体"+data);
			        	
			        	if(!data.arealevel){
				            
			        		var infoTitle = data.entername + '：SO2许可排放量（单位：KG）';
				        	var infoBody =  '<div class="poi-info-left">' +
						                    '    <h3 class="poi-title">' +
						                    '    </h3>' +
						                    '    <div class="poi-info">' +
						                    '        <p class="poi-addr">排放量：'+data.count +'&nbsp;&nbsp;&nbsp;&nbsp;占比：'+data.rate+'%</p>' +
						                    '    </div>' +
						                    '</div>' +
						                    '<div class="clear"></div>';

				            return new SimpleInfoWindow({
				                infoTitle: infoTitle,
				                infoBody:  infoBody,
				                offset: new AMap.Pixel(0, -37)
				            });
			        	}
			        	
			        	var infoTitle = data.areaname + '：SO2许可排放量（单位：KG）';
			        	var infoBody =  '<div class="poi-info-left">' +
					                    '    <h3 class="poi-title">' +
					                    '    </h3>' +
					                    '    <div class="poi-info">' +
					                    '        <p class="poi-addr">排放量：'+data.count +'&nbsp;&nbsp;&nbsp;&nbsp;占比：'+data.rate+'%</p>' +
					                    '    </div>' +
					                    '</div>' +
					                    '<div class="clear"></div>';
			            if (recycledInfoWindow) {

			                recycledInfoWindow.setInfoTitle(infoTitle);
			                recycledInfoWindow.setInfoBody(infoBody);

			                return recycledInfoWindow;
			            }

			            return new SimpleInfoWindow({
			                infoTitle: infoTitle,
			                infoBody:  infoBody,
			                offset: new AMap.Pixel(0, -37)
			            });
			        },
			        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
			        getMarker: function(data, context, recycledMarker) {
			        	//console.log('地区级别：'+data.areaLevel);
			        	//console.log('getMarker：'+data);
			            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);
			            /*
			            if (recycledMarker) {
			                recycledMarker.setIconLabel(label);
			                return;
			            }
			           */
			        	
			        	if(!data.arealevel){
				            return new SimpleMarker({
				                containerClassNames: 'my-marker',
				                iconStyle: defaultIconStyle,
				                iconLabel: label
				            });
			        	}
			        	
			        	if(emissionML.cityMarker && emissionML.inited) {
			        		return emissionML.cityMarker[context.index];
			        	}
			        	return emissionML.createCustomMarker(data, context.index);
			        },
			        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
			        getListElement: function(data, context, recycledListElement) {

			            var label = context.index+1;
			            
			            
			            if(!data.arealevel){
			            	var innerHTML = MarkerList.utils.template(
				                    '<div class="poi-info-left">' +
				                    '    <h3 class="poi-title">' +
				                    '        <%- label %>. <%- data.entername %>' + "：" +
				                    '    </h3>' +
				                    '    <div class="poi-info">' +
				                    '        <p class="poi-addr">排放量：<%- data.count %>&nbsp;&nbsp;&nbsp;&nbsp;占比：<%- data.rate %>%</p>' +
				                    '    </div>' +
				                    '</div>' +
				                    '<div class="clear"></div>', {
				                        data: data,
				                        label: label
				                    });

				            return 	'<li class="poibox">' +
					                innerHTML +
					                '</li>';
			        	}

			            //./images/guo.png
			            var innerHTML = MarkerList.utils.template(
			                    '<div class="poi-info-left">' +
			                    '    <h3 class="poi-title">' +
			                    '        <%- label %>. <%- data.areaname %>' + '：SO2许可排放量（单位：KG）' + 
			                    '    </h3>' +
			                    '    <div class="poi-info">' +
			                    '        <p class="poi-addr">排放量：<%- data.count %>&nbsp;&nbsp;&nbsp;&nbsp;占比：<%- data.rate %>%</p>' +
			                    '    </div>' +
			                    '</div>' +
			                    '<div class="clear"></div>', {
			                        data: data,
			                        label: label
			                    });

			            if (recycledListElement) {
			                recycledListElement.innerHTML = innerHTML;
			                return recycledListElement;
			            }

			            return 	'<li class="poibox">' +
				                innerHTML +
				                '</li>';
			        },
			        //列表节点上监听的事件
			        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
			        //marker上监听的事件
			        markerEvents: ['click', 'mouseover', 'mouseout'],
			        //makeSelectedEvents:false,
			        selectedClassNames: 'selected',
			        autoSetFitView: true
			    });

			    //window.markerList = markerList;
			    emissionML.markerList = markerList;

			    emissionML.goPage(1);
			    
			    AMap.event.addListener(gis.map, 'zoomend', emissionML._onZoomEnd);

			    markerList.on('selectedChanged', function(event, info) {

			        if (info.selected) {

			            //console.log(info);
			            
			            if (info.selected.marker) {
			                //更新为选中样式
			                //info.selected.marker.setIconStyle(selectedIconStyle);
			            }

			            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
			            if (!info.sourceEventInfo.isListElementEvent) {

			                if (info.selected.listElement) {
			                    scrollListElementIntoView($(info.selected.listElement));
			                }
			            }
			        }

			        if (info.unSelected && info.unSelected.marker) {
			            //更新为默认样式
			            //info.unSelected.marker.setIconStyle(defaultIconStyle);
			        }
			    });

			    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

			        if (record && record.marker) {

			            forcusMarker(record.marker);

			            //this.openInfoWindowOnRecord(record);

			            //非选中的id
			            if (!this.isSelectedDataId(record.id)) {
			                //设置为hover样式
			                //record.marker.setIconStyle(hoverIconStyle);
			                //this.closeInfoWindow();
			            }
			        }
			    });

			    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

			        if (record && record.marker) {

			            if (!this.isSelectedDataId(record.id)) {
			                //恢复默认样式
			                //record.marker.setIconStyle(defaultIconStyle);
			            }
			        }
			    });

			    //数据输出完成
			    markerList.on('renderComplete', function(event, records) {

			    });

			    // markerList.on('*', function(type, event, res) {
			    //     console.log(type, event, res);
			    // });

			    function forcusMarker(marker) {
			        marker.setTop(true);

			        //不在地图视野内
			        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

			            //移动到中心
			        	gis.map.setCenter(marker.getPosition());
			        }
			    }

			    function isElementInViewport(el) {
			        var rect = el.getBoundingClientRect();

			        return (
			            rect.top >= 0 &&
			            rect.left >= 0 &&
			            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
			            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
			        );
			    }

			    function scrollListElementIntoView($listEle) {

			        if (!isElementInViewport($listEle.get(0))) {
			            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
			            //console.log($listEle.offset().top - $listEle.parent().offset().top);
			        }

			        //闪动一下
			        $listEle
			            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
			                function(e) {
			                    $(this).removeClass('flash animated');
			                }).addClass('flash animated');
			    }
			});
		},
		
		/**
		 * 重新渲染MarkerList
		 */
		reRenderData:function(data){
			emissionML.goPage(1);
		},
		
		/**
		 * 1、销毁MarkerList
		 * LMarkerList下的数据cityData、cityMarker、sublist只是简单重置，已使用的内存不一定得到释放
		 * 2、全省的许可证数量汇总面板，被清空
		 */
		clearData: function(){
			console.log('销毁LMarkerList：'+emissionML.markerList);
			if(emissionML.markerList && emissionML.markerList.getData() && emissionML.markerList.getData().length>0) {
				emissionML.markerList.clearData();
				
				emissionML.inited = false;
				emissionML.cityData = [];
				emissionML.cityDataLength = 0;
				emissionML.cityMarker = [];
				emissionML.sublist = [];
			}
		},
		
		 /**
	     * 地图上的收缩响应事件，重新渲染饼状图，清掉企业点位
	     */
		_onZoomEnd : function(e) {
	        if (gis.map.getZoom() <= 8) {
	        	//这里要检查一下地图是否已经存在数据了，存在不应该重新渲染了
	        	emissionML.markerList.render(emissionML.cityData);
	        }/*else {
	        	//地图放大会多次进入该方法...出现错乱渲染
	        	emissionML.markerList.render(emissionML.sublist);
	        }*/
	    },
	    
	    /**
	     * 地图上的饼状图点击响应事件，渲染该地市下面的企业点位信息，清掉饼状图
	     */
	    _onClick : function(e) {
	    	console.log(e);
	    	console.log(e.target.getExtData());
	    	emissionML.markerList.render(e.target.getExtData());
	    },
	    
		/** 
		 * 添加自定义标注 
		 */  
		createCustomMarker: function(data, divNumber){    
			/** 
		     * 自定义覆盖物dom元素   
		     */ 
			var marker = emissionML._renderCluserMarker(data);  
		      
		    if(!emissionML.inited && emissionML.cityDataLength>emissionML.cityMarker.length){
		    	emissionML.cityMarker.push(marker);
		    }
		    if(emissionML.cityDataLength == emissionML.cityMarker.length){
		    	emissionML.inited = true;
		    }
		    marker.setExtData(data.sublist);
		    AMap.event.addListener(marker, 'click', emissionML._onClick);
		    
	        return marker;
		},
		
		_renderCluserMarker : function (data) {
	        var factor = Math.pow(data.count/data.total,1/18)
	        var div = document.createElement('div');
	        var Hue = 180 - factor* 180;
	        var bgColor = 'hsla('+Hue+',100%,50%,0.7)';
	        var fontColor = 'hsla('+Hue+',100%,20%,1)';
	        var borderColor = 'hsla('+Hue+',100%,40%,1)';
	        var shadowColor = 'hsla('+Hue+',100%,50%,1)';
	        div.style.backgroundColor = bgColor
	        var size = Math.round(30 + Math.pow(data.count/data.total,1/5) * 20);
	        div.style.width = div.style.height = size+'px';
	        div.style.border = 'solid 1px '+ borderColor;
	        div.style.borderRadius = size/2 + 'px';
	        div.style.boxShadow = '0 0 1px '+ shadowColor;
	        div.innerHTML = data.count;
	        div.style.lineHeight = size+'px';
	        div.style.color = fontColor;
	        div.style.fontSize = '14px';
	        div.style.textAlign = 'center';
	        
	        var marker = new AMap.Marker({    
		        map:gis.map,
		        position:new AMap.LngLat(data.longitude, data.latitude), //基点位置    
		        offset: new AMap.Pixel(-size/2,-size/2),
		        //draggable:true,  //是否可拖动    
		        content:div   //自定义覆盖物内容    
		    });  
	        return marker;
	     }
	};
	
	return emissionML;
});